<?php

namespace app\tools;

use Yii;
use app\tools\Curl;
use app\tools\Grab;
use app\tools\Wechat;

class Wechat {
  //微信公众号相关操作

  //获取access_token
  public static function getAccessToken(){
    $appid = Yii::$app->params['wechatConfig']['app_id'];
    $appsecret = Yii::$app->params['wechatConfig']['secret'];
    $redis_key = 'lxj_xcx_access_token_'. $appid;
    $redis_value = Yii::$app->redis->get($redis_key);
    if ($redis_value) {
      $access_token = $redis_value;
    } else {
      $access_token = '';
      $response = Curl::curl_get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret");
      if ( $response) {
        $ret = json_decode($response, true);
        if($ret and isset($ret['access_token'])) {
          $access_token = $ret['access_token'];
          Yii::$app->redis->set($redis_key, $access_token);
          Yii::$app->redis->expire($redis_key, 5000);
        }
      }
    }
		return $access_token;
  }
}
